package com.woniuxy.service.impl;


import com.woniuxy.dao.OrderDao;
import com.woniuxy.entity.Order;
import com.woniuxy.entity.Product;
import com.woniuxy.entity.utils.ResponseEntity;
import com.woniuxy.service.OrderService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


//@Service
public class OrderServiceImpl1 implements OrderService {
    static int times =0;
    @Autowired
    OrderDao orderDao;

    @Autowired
    DiscoveryClient discoveryClient;

    @Override
    public Order addOne(Order order) {
        return  orderDao.save(order);
    }

    @Override
    public ResponseEntity generateOrder(Integer pid, Integer num) {
        List<String> urls = this.allURL();
        times++;
        RestTemplate restTemplate=new RestTemplate();
        ResponseEntity productResp=restTemplate.getForObject("http:/localhost:8081/product"+pid,ResponseEntity.class);
        Product product = new Product();
        if(Integer.parseInt(productResp.get(ResponseEntity.ResponseStatus.CODE.value())+"")== HttpStatus.INTERNAL_SERVER_ERROR.value()){
            return productResp;
        }
        Map map= (Map) productResp.get(ResponseEntity.ResponseStatus.DATA.value());
        try {

            BeanUtils.populate(product,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        Order order = new Order();
        //用户信息假数据
        order.setUid(1);
        order.setUsername("马蜂窝");
        order.setPid(product.getPid());
        order.setPname(product.getName());
        order.setPrice(product.getPrice());

        order.setNumber(num);
        Order returnOrder = null;

        if (product.getStock()-num>=0) {
            returnOrder = orderDao.save(order);
            product.setStock(product.getStock()-num);
            restTemplate.put("http://localhost:8081/product/", product);
        }else{
            return new ResponseEntity(HttpStatus.NOT_MODIFIED.value(),"商品卖完了。");
        }

        return new ResponseEntity(returnOrder);
    }

    public List<String> allURL(){
        List<String> urls = new ArrayList<>();
        urls.add("http://localhost:8081/product/");
        urls.add("http://localhost:8083/product/");
        urls.add("http://localhost:8084/product/");
        return urls;
    }
}
